<template>
  <div v-if="show" class="numcard numcardItem1">
    <span class="real-time-num gsapNum" ref="number">{{ formattedNumber }}</span>
  </div>
</template>

<script>
import gsap from 'gsap'

export default {
  data () {
    return {
      rawNumber: 0, // 更改为rawNumber，存储实际数字值
      show: true,
      showComma: false // 是否显示千分位逗号
    }
  },
  props: {
    number: {
      type: [Number, String],
      default () {
        return 0
      }
    },
    decimal: { // 新增属性用于控制是否显示两位小数
      type: Boolean,
      default: false
    },
    comma: { // 通过props控制是否显示千分位
      type: Boolean,
      default: false
    },
    delay: {
      type: [Number, String],
      default () {
        return 0
      }
    }
  },
  computed: {
    formattedNumber () {
      let number = this.rawNumber
      // console.log(number)
      if (number === 0) {
        return "暂无数据";
      }
      if (this.showComma) {
        number = number.toLocaleString()
      }
      if (this.decimal) {
        number = number.toFixed(2) // 格式化为两位小数
      }
      return number
    },
    currentNumber: {
      get () {
        return this.rawNumber
      },
      set (value) {
        this.rawNumber = value
      }
    }
  },
  watch: {
    number (newVal) {
      if (this.show) {
        this.$nextTick(() => {
          this.currentNumber = 0
          this.animateNumber(this.currentNumber, newVal)
        })
      }
    },
    show () {
      this.$nextTick(() => {
        this.currentNumber = 0
        this.animateNumber(this.currentNumber, this.number)
      })
    },
    comma (newVal) {
      this.showComma = newVal // 设置是否显示千分位
    }
  },
  methods: {
    animateNumber (start, end) {
      gsap.to(this, {
        currentNumber: end,
        duration: 2,
        delay: parseFloat(this.delay),
        roundProps: 'currentNumber',
        ease: 'power1.out',
        onUpdate: () => {
          console.log(this.currentNumber)
          this.currentNumber = Math.round(this.currentNumber)
        }
      })
    }
  },
  mounted () {
    this.showComma = this.comma
    this.showDecimal = this.decimal // 初始化显示小数的设置
    if (this.show) {
      this.currentNumber = 0
      console.log(this.number)
      this.animateNumber(this.currentNumber, this.number)
    }
  }
}
</script>

<style lang="scss">
.numcardItem1 {
  .real-time-num {
    width: auto !important;
    font-size: 30px;
    font-family: DIN-Bold, DIN;
    font-weight: bold;
    color: #31FFFD;
  }
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}
</style>
